﻿/// <reference path="jquery-1.4.4-vsdoc.js" />
var Common = {

    //EasyUI用DataGrid用日期格式化
    DateTimeFormatter: function (value, rec, index) {
        if (value == undefined) {
            return "";
        }

        /*json格式时间转js时间格式*/
        value = value.substr(1, value.length - 2);
        var obj = eval('(' + "{Date: new " + value + "}" + ')');
        var dateValue = obj["Date"];

        if (dateValue.format("yyyy") == "1900") {
            return "";
        }

        return dateValue.format("yyyy-mm-dd HH:MM:ss");
    },

    //EasyUI用DataGrid用日期格式化
    DateFormatter: function (value, rec, index) {
        if (value == undefined) {
            return "";
        }
        try {
            /*json格式时间转js时间格式*/
            value = value.substr(1, value.length - 2);
            var obj = eval('(' + "{Date: new " + value + "}" + ')');
            var dateValue = obj["Date"];
            var d = dateValue.format("yyyy-mm-dd");
            if (d == "1900-01-01") {
                return "";
            } else {
                return d;
            }
        } catch (e) {
            return "";
        }
    },
    //呈现新选项卡
    ShowTab: function (e, title, refresh, isIframe) {
        if (title == null) {
            if (typeof (e) != "string")
                title = $(e).text();
        }

        //判断是否重新打开新窗口,不重新打开判断是否已打开此页面
        if (!refresh) {
            if ($('#tabsMain').tabs('exists', title)) {
                $('#tabsMain').tabs('select', title);

                try {
                    //刷新列表
                    $(".tabs-panels .panel:visible").find("table[idfield][url][id]").datagrid("load", { queryParams: "" });
                } catch (e) {
                }
                return true;
            }
        }
        var url = "";
        if (typeof (e) == "string")
            url = e;
        else
            url = $(e).attr("href");

        if (isIframe) {
            if ($('#tabsMain').tabs('exists', title)) {
                $('#tabsMain').tabs('close', title);
            }
            var content = "<iframe  onload='Javascript:Common.SetIframeAutoHeight(this)' scrolling='no' frameborder='0'  src='" + url + "' style='width:100%;height:100%;'></iframe>";
            $('#tabsMain').tabs('add', {
                title: title,
                content: content,
                closable: true
            });
        }
        else {
            $.get(url, function (data) {
                if ($('#tabsMain').tabs('exists', title)) {
                    $('#tabsMain').tabs('close', title);
                }

                $('#tabsMain').tabs('add', {
                    title: title,
                    content: data,
                    closable: true
                });

                //绑定搜索、块折叠脚本
                Common.BindSearch($(".tabs-panels .panel:visible"));
                Common.BindWarp($(".tabs-panels .panel:visible"));
            });
        }

        return false;
    },

    //关闭当前选项卡
    CloseTab: function () {
        var tab = $('#tabsMain').tabs('getSelected');
        $('#tabsMain').tabs('close', tab.panel('options').title);
    },
    SetIframeAutoHeight: function (e) {
        $(e).height($(e).contents().height() - 5);
    },

    IsIdCardNo: function (IdCard) {
        var reg = /^\d{15}(\d{2}[0-9X])?$/i;
        if (!reg.test(IdCard)) {
            return false;
        }

        if (IdCard.length == 15) {
            var n = new Date();
            var y = n.getFullYear();
            if (parseInt("19" + IdCard.substr(6, 2)) < 1900 || parseInt("19" + IdCard.substr(6, 2)) > y) {
                return false;
            }

            var birth = "19" + IdCard.substr(6, 2) + "-" + IdCard.substr(8, 2) + "-" + IdCard.substr(10, 2);
            if (!Common.IsDate(birth)) {
                return false;
            }
        }
        if (IdCard.length == 18) {
            var n = new Date();
            var y = n.getFullYear();
            if (parseInt(IdCard.substr(6, 4)) < 1900 || parseInt(IdCard.substr(6, 4)) > y) {
                return false;
            }

            var birth = IdCard.substr(6, 4) + "-" + IdCard.substr(10, 2) + "-" + IdCard.substr(12, 2);
            if (!Common.IsDate(birth)) {
                return false;
            }

            iW = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);

            iSum = 0;
            for (i = 0; i < 17; i++) {
                iC = IdCard.charAt(i);
                iVal = parseInt(iC);
                iSum += iVal * iW[i];
            }

            iJYM = iSum % 11;
            if (iJYM == 0) sJYM = "1";
            else if (iJYM == 1) sJYM = "0";
            else if (iJYM == 2) sJYM = "x";
            else if (iJYM == 3) sJYM = "9";
            else if (iJYM == 4) sJYM = "8";
            else if (iJYM == 5) sJYM = "7";
            else if (iJYM == 6) sJYM = "6";
            else if (iJYM == 7) sJYM = "5";
            else if (iJYM == 8) sJYM = "4";
            else if (iJYM == 9) sJYM = "3";
            else if (iJYM == 10) sJYM = "2";

            var cCheck = IdCard.charAt(17).toLowerCase();
            if (cCheck != sJYM) {
                return false;
            }
        }
        return true;
    },

    IsDate: function (strDate) {
        var strSeparator = "-"; //日期分隔符
        var strDateArray;
        var intYear;
        var intMonth;
        var intDay;
        var boolLeapYear;
        strDateArray = strDate.split(strSeparator);
        if (strDateArray.length != 3) return false;
        intYear = parseInt(strDateArray[0], 10);
        intMonth = parseInt(strDateArray[1], 10);
        intDay = parseInt(strDateArray[2], 10);
        if (isNaN(intYear) || isNaN(intMonth) || isNaN(intDay)) return false;
        if (intMonth > 12 || intMonth < 1) return false;
        if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) return false;
        if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) return false;
        if (intMonth == 2) {
            if (intDay < 1) return false;
            boolLeapYear = false;
            if ((intYear % 100) == 0) {
                if ((intYear % 400) == 0) boolLeapYear = true;
            }
            else {
                if ((intYear % 4) == 0) boolLeapYear = true;
            }
            if (boolLeapYear) {
                if (intDay > 29) return false;
            }
            else {
                if (intDay > 28) return false;
            }
        }
        return true;
    }
};
//标题收缩展开
Common.BindWarp = function (e) {
    var arr = null;
    if (e) {
        arr = $(e).find(".tg-left");
    }
    else {
        arr = $(".tg-left");
    }
    arr.each(function (i, n) {
        if ($(n).hasClass("tgd-l")) {
            $(n).next().show();
        }
        else {
            $(n).next().hide();
        }

        if (!$(n).hasClass("no-warp")) {
            $(n).unbind("click");
            $(n).click(function () {
                if ($(this).hasClass("tgd-l")) {
                    $(this).removeClass("tgd-l");
                    $(this).next().hide();
                }
                else {
                    $(this).addClass("tgd-l");
                    $(this).next().show();
                }
            });
        }
    });
};

//绑定高级搜索事件
Common.BindSearch = Common.BindAdvSearch = function (e) {
    var arr = null;
    if (e) arr = $(e).find(".expand-tgd-advsearch, .expand-tg-advsearch");
    else arr = $(".expand-tgd-advsearch, .expand-tg-advsearch");

    //绑定事件
    arr.unbind("click");
    arr.click(function () {
        if (this.className == 'expand-tgd-advsearch') {
            //$("#advsearch").slideDown("normal");
            $(this).parents(".tt-attach").next().slideDown("normal");
            $(this).removeClass('expand-tgd-advsearch').addClass('expand-tg-advsearch').html('收起搜索');
        }
        else {
            //$("#advsearch").slideUp("normal");
            $(this).parents(".tt-attach").next().slideUp("normal");
            $(this).removeClass('expand-tg-advsearch').addClass('expand-tgd-advsearch').html('高级搜索');
        }
    });

    var arr2 = null;
    if (e) arr2 = $(e).find(".expand-tgd-Statistics, .expand-tg-Statistics");
    else arr2 = $(".expand-tgd-Statistics, .expand-tg-Statistics");

    //绑定事件
    arr2.unbind("click");
    arr2.click(function () {
        if (this.className == 'expand-tgd-Statistics') {
            //$("#advsearch").slideDown("normal");
            $(this).parents(".tt-attach").next().slideDown("normal");
            $(this).removeClass('expand-tgd-Statistics').addClass('expand-tg-Statistics').html('收起统计');
        }
        else {
            //$("#advsearch").slideUp("normal");
            $(this).parents(".tt-attach").next().slideUp("normal");
            $(this).removeClass('expand-tg-Statistics').addClass('expand-tgd-Statistics').html('统计');
        }
    });


    //绑定高级搜索输入框回车事件
    arr.each(function (i, n) {
        var texts = $(n).parents(".tt-attach").next().find(":text");
        texts.unbind("keydown");
        texts.keydown(function () {
            if (event.which == 13) {
                $(this).parents(".advsearch").find(":button").focus();
            }
        });
    });

    //绑定搜索输入框回车事件
    var inputs = null;
    if (e) inputs = $(e).find(".search-text");
    else inputs = $(".search-text");
    inputs.unbind("keydown");
    inputs.keydown(function () {
        if (event.keyCode == 13 || event.which == 13) {
            $(this).next().focus();
        }
    });
};

//列表加载完成事件
//重新设计列表高度，避免tab出现滚动条
//修改easyui-lang-zh_CN.js,添加如下
//if ($.fn.datagrid) {
//    $.fn.datagrid.defaults.onLoadSuccess = function () { Common.DataGridLoad(); };
//}
Common.DataGridLoad = function (e, run) {
    if (!run) {
        setTimeout("Common.DataGridLoad(null,true);", 10);
        return;
    }

    //tab标签内容高度
    var tabHeight = $('#tbList').parents(".tabs-panels").height();

    //当前标签滚动条高度
    var scrollHeight = $('#tbList').parents(".tabs-panels").find(".panel-body")[0].scrollHeight;

    //列表高度
    var gridHeight = $('#tbList').parents(".datagrid-wrap").height();

    //列表内容高度
    var bodyHeight = $('#tbList').parents(".datagrid-wrap").find(".datagrid-body").height();

    //列表内容列表高度
    var tableHeight = $('#tbList').parents(".datagrid-wrap").find(".datagrid-body").children().height();

    //alert(bodyHeight + "-" + tableHeight + ",-scrollHeight=" + scrollHeight + "--" + tabHeight);
    if (tabHeight < scrollHeight) {
        //除datagrid外其它元素占用高度
        var otherHeight = scrollHeight - gridHeight;
        $('#tbList').datagrid("resize", { height: tabHeight - otherHeight });
        //        $('#tbList').parents(".datagrid-wrap").css("height", 613);
        //        $('#tbList').parents(".datagrid-view").css("height", 582);
        //        $('#tbList').parents(".datagrid-wrap").find(".datagrid-view2 .datagrid-body").children().css("height", 552);
        //        $('#tbList').parents(".datagrid-wrap").find(".datagrid-view2 .datagrid-body").css("overflow", "auto");

    }
    else if (bodyHeight > tableHeight) {
        $('#tbList').datagrid("resize", { height: "auto" });
    }
};


//获取事件
Common.GetEvent = function () {
    //如果是ie
    if (document.all) {
        return window.event;
    }
    var func = Common.GetEvent.caller;
    while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0) {
            if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                return arg0;
            }
        }
        func = func.caller;
    }
    return null;
};



/*
* Date Format 1.2.2
* (c) 2007-2008 Steven Levithan <stevenlevithan.com>
* MIT license
* Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date();
        if (isNaN(date)) throw new SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d: d,
                dd: pad(d),
                ddd: dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m: m + 1,
                mm: pad(m + 1),
                mmm: dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy: String(y).slice(2),
                yyyy: y,
                h: H % 12 || 12,
                hh: pad(H % 12 || 12),
                H: H,
                HH: pad(H),
                M: M,
                MM: pad(M),
                s: s,
                ss: pad(s),
                l: pad(L, 3),
                L: pad(L > 99 ? Math.round(L / 10) : L),
                t: H < 12 ? "a" : "p",
                tt: H < 12 ? "am" : "pm",
                T: H < 12 ? "A" : "P",
                TT: H < 12 ? "AM" : "PM",
                Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};
